import os
import subprocess
import sys
import multiprocessing
import time

from PyQt5.QtCore import Qt, QPoint, QLineF, QUrl
from PyQt5.QtGui import QPixmap, QIcon, QPainter, QLinearGradient, QColor, QPen
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMainWindow
# from PyQt5.QtWebEngineWidgets import QWebEngineView

from asr import ASRWindow

script_dir = os.path.dirname(__file__)

set_num = 0
sym_num = 0

# class SymbolWindow(QMainWindow):
#     def __init__(self):
#         super().__init__()
#         script_dir = os.path.dirname(__file__)
#         file_path = os.path.join(script_dir, 'static/symbols.html')
#         self.setWindowTitle('   ')
#         # 创建图标对象
#         icon = QIcon(os.path.join(script_dir, 'static/images/trayImages/状态栏logo.png'))
#         # 设置窗口图标
#         self.setWindowIcon(icon)
#         self.resize(800, 578)
#         self.web_view = QWebEngineView()
#         self.web_view.setUrl(QUrl.fromLocalFile(file_path))
#         layout = QVBoxLayout()
#         layout.addWidget(self.web_view)
#         widget = QWidget()
#         widget.setLayout(layout)
#         self.setCentralWidget(widget)
#
#     def closeEvent(self, event):
#         event.ignore()
#         self.hide()
#         #subprocess.run(["/usr/share/fcitx/Oyun/OyunUI/oyun/bin/python","/usr/share/fcitx/Oyun/OyunUI/closetray.py"])
#         # p = multiprocessing.Process(target=worker)
#         # p.start()
#
#     # def showEvent(self, event):
#     #     tray_available = subprocess.run(["pgrep","-f","closetray.py"], stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
#     #     for tray_id in tray_available:
#     #         subprocess.run(["kill",tray_id])
#
#
# class SettingWindow(QMainWindow):
#     def __init__(self):
#         super().__init__()
#         file_path = os.path.join(script_dir, 'static/index.html')
#         self.setWindowTitle('   '  )
#         # 创建图标对象
#         icon = QIcon(os.path.join(script_dir, 'static/images/trayImages/状态栏logo.png'))
#         # 设置窗口图标
#         self.setWindowIcon(icon)
#         self.resize(1000, 700)
#         self.web_view = QWebEngineView()
#         self.web_view.setUrl(QUrl.fromLocalFile(file_path))
#         layout = QVBoxLayout()
#         layout.addWidget(self.web_view)
#         widget = QWidget()
#         widget.setLayout(layout)
#         self.setCentralWidget(widget)
#
#     def closeEvent(self, event):
#         event.ignore()
#         self.hide()
#         #subprocess.run(["/usr/share/fcitx/Oyun/OyunUI/oyun/bin/python","/usr/share/fcitx/Oyun/OyunUI/closetray.py"])
#         # p = multiprocessing.Process(target=worker)
#         # p.start()
#
#     # def showEvent(self, event):
#     #     tray_available = subprocess.run(["pgrep","-f","closetray.py"], stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
#     #     for tray_id in tray_available:
#     #         subprocess.run(["kill",tray_id])


class InputMethodStatusWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Input Method Status")
        self.setWindowIcon(QIcon(os.path.join(script_dir, "static/icon.png")))
        # 状态栏图标个数
        num = 6
        self.setGeometry(300, 300, 32 + 26 * num, 32)
        self.setWindowFlags(
            Qt.WindowType.Popup |
            Qt.WindowType.Tool
            | Qt.FramelessWindowHint
            | Qt.WindowStaysOnTopHint
        )
        self.setAttribute(Qt.WA_TranslucentBackground)

        # logo图标
        btn = QPushButton(self)
        btn.setGeometry(1, 1, 30, 30)
        btn.mousePressEvent = self.onMousePress
        btn.mouseMoveEvent = self.onMouseMove
        btn.mouseReleaseEvent = lambda event, release_func=None: self.onMouseRelease(event, release_func)
        image_path = os.path.join(script_dir, 'static/images/trayImages/状态栏logo.png')
        image_path = image_path.replace('\\', '/')
        btn.setStyleSheet("""
                          QPushButton {
                            background-image: url('%s');
                            background-repeat: no-repeat;
                            background-position: center;
                            border-radius: 20px;
                          }
                          """ % image_path)
        # 状态栏图标
        buttons_info = {
            'language': {'icon': '蒙语.png', 'release_func': self.onLanguageRelease},
            'symbol': {'icon': '符号.png', 'release_func': self.onSymbolRelease},
            'voice': {'icon': '话筒.png', 'release_func': self.onVoiceRelease},
            'keyboard': {'icon': '软键盘.png', 'release_func': self.onKeyboardRelease},
            'skin': {'icon': '皮肤.png', 'release_func': self.onSkinRelease},
            'settings': {'icon': '设置.png', 'release_func': self.onSettingsRelease},
        }
        # 创建默认背景颜色'images/')))
        default_bg_color = QColor(255, 255, 255)

        # 创建渐变对象
        gradient = QLinearGradient(0, 0, 100, 100)
        gradient_stops = [
            (0, QColor("#ede5ff")),
            (0.5, QColor("#e7e7fe")),
            (1, QColor("#c9f1fd"))
        ]
        for stop in gradient_stops:
            gradient.setColorAt(stop[0], stop[1])

        for i, (button_name, button_info) in enumerate(buttons_info.items()):
            default_icon = QIcon(
                QPixmap(os.path.join(script_dir, f"static/images/trayImages/inactive/{button_info['icon']}")))
            hover_icon = QIcon(
                QPixmap(os.path.join(script_dir, f"static/images/trayImages/active/{button_info['icon']}")))

            def set_button_icons(btn, default_icon, hover_icon):
                btn.setIcon(default_icon)

                btn.enterEvent = lambda event: btn.setIcon(hover_icon)
                btn.leaveEvent = lambda event: btn.setIcon(default_icon)

            btn = QPushButton(self)
            set_button_icons(btn, default_icon, hover_icon)

            btn.setGeometry(31 + i * 26, 3, 26, 26)
            btn.mousePressEvent = self.onMousePress
            btn.mouseMoveEvent = self.onMouseMove
            btn.mouseReleaseEvent = lambda event, release_func=button_info['release_func']: self.onMouseRelease(event,
                                                                                                                release_func)
            btn.setStyleSheet("""
                QPushButton {
                    background-color: %s;
                    border: none;
                    padding: 5px;
                    color: #333333;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 %s, stop:0.5 %s, stop:1 %s);
                    color: #ffffff;
                }
            """ % (default_bg_color.name(), gradient_stops[0][1].name(), gradient_stops[1][1].name(),
                   gradient_stops[2][1].name()))

        self.layout = QVBoxLayout()
        self.layout.addStretch()
        self.setLayout(self.layout)

        desktop = QApplication.desktop()
        screen_rect = desktop.screenGeometry(desktop.primaryScreen())
        screen_width = screen_rect.width()
        screen_height = screen_rect.height()

        self.move(screen_width - self.width() - 100, screen_height - self.height() - 100)

        self.mousePressed = False
        self.mousePressPos = QPoint(0, 0)
        self.windowPressPos = QPoint(0, 0)

        self.symbol_window = SymbolWindow()
        # self.asr_window = ASRWindow()
        # self.setting_window = SettingWindow()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)

        # 绘制边框
        color = QColor("#02A7F0")
        pen = QPen(color)
        pen.setWidth(1)
        painter.setPen(pen)
        painter.drawRect(5, 3, self.width() - 5, self.height() - 6)

    def onMousePress(self, event):
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        if event.button() == Qt.LeftButton:
            self.mousePressed = True
            self.mousePressPos = event.globalPos()
            self.windowPressPos = self.pos()

    def onMouseMove(self, event):
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        if self.mousePressed and event.buttons() == Qt.LeftButton:
            globalPos = event.globalPos()
            diff = globalPos - self.mousePressPos
            newPos = self.windowPressPos + diff
            self.move(newPos)

    def onMouseRelease(self, event, release_func):
       # subprocess.run(["fcitx-remote", "-s","Oyun"])
        if event.button() == Qt.LeftButton:
            self.mousePressed = False
            distance = QLineF(event.globalPos(), self.mousePressPos).length()
            if distance < 10 and release_func is not None:
                release_func(event)
    # def openSetting(self):
    #     self.setting_window = SettingWindow()
    #     self.setting_window.show()
    #     print("123")

    def onSettingsRelease(self, event):
        global set_num
        #subprocess.run(["/usr/bin/qaxbrowser-safe-stable", "--app='file:///usr/share/fcitx/web/static/index.html'"])
        if set_num == 0:
            url = "file:///usr/share/fcitx/Oyun/OyunUI/static/index.html"
            # set_num += 1
            p = multiprocessing.Process(target=worker,args=(url,))
            p.start()
            # p.atexit = end_set
        # if not self.setting_window.isVisible():
        #     self.setting_window = SettingWindow()
        #     self.setting_window.show()
      #      subprocess.run(["fcitx-remote", "-s","Oyun"])
    def onLanguageRelease(self, event):
        subprocess.run(["fcitx-remote", "-t"])
        QApplication.quit()

    def onSymbolRelease(self, event):
        #subprocess.run(["/usr/bin/qaxbrowser-safe-stable", "--app","file:///usr/share/fcitx/web/static/symbols.html"])
        global sym_num
        if sym_num ==0:
            url = "file:///usr/share/fcitx/Oyun/OyunUI/static/symbols.html"
            # sym_num +=1
            p = multiprocessing.Process(target=worker,args=(url,))
            p.start()
            # p.atexit = end_sym
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        # if not self.symbol_window.isVisible():
        #     self.symbol_window = SymbolWindow()
        #     self.symbol_window.show()

    def onVoiceRelease(self, event):
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        if not self.asr_window.isVisible():
           # tray_available = subprocess.run(["pgrep","-f","closetray.py"], stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
           #  for tray_id in tray_available:
           #      subprocess.run(["kill",tray_id])
            self.asr_window = ASRWindow()
            self.asr_window.show()

    def onKeyboardRelease(self, event):
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        print("Keyboard button released")

    def onSkinRelease(self, event):
        #subprocess.run(["fcitx-remote", "-s","Oyun"])
        print("Skin button released")


def worker(url):
    html = "/usr/bin/qaxbrowser-safe-stable --app=" + url 
    os.system(html)


# def end_set():
#     set_num -= 1

# def end_sym():
#     sym_num -=1
if __name__ == "__main__":
    tray_available = subprocess.run(["pgrep","-f","trayWindow.py"], stdout=subprocess.PIPE).stdout.decode('utf-8')
    print("tray_num")
    print(len(tray_available.splitlines()))
    tray_available = len(tray_available.splitlines())
    if tray_available > 2:
        sys.exit(0)
    app = QApplication(sys.argv)

    # im_num = subprocess.run(["fcitx-remote"], stdout=subprocess.PIPE).stdout.decode('utf-8')[0]
    # with open('/usr/share/fcitx/Oyun/OyunUI/Oyun_index', 'w') as f:
    #     f.write(im_num)
    # p = multiprocessing.Process(target=worker)
    # p.start()
    window = InputMethodStatusWindow()
    window.show()
    sys.exit(app.exec_())
